package com.magicborrow.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.google.gson.Gson;
import com.magicborrow.Constants;
import com.magicborrow.MagicBorrowApplication;
import com.magicborrow.R;
import com.magicborrow.beans.UserBean;
import com.magicborrow.utils.HttpRequest;
import com.magicborrow.utils.ImageUploadAsyncTask;
import com.magicborrow.utils.UmengUtils;
import com.magicborrow.utils.UserTools;
import com.magicborrow.views.LoadingDialog;
import com.mob.tools.utils.UIHandler;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;


public class FirstRegisterActivity extends BaseActivity implements View.OnClickListener, PlatformActionListener, Handler.Callback {

    private LinearLayout weixinRegister;
    private TextView elseRegister;
    private TextView longins;
    private TextView enter;

    private static final int MSG_USERID_FOUND = 1;
    private static final int MSG_LOGIN = 2;
    private static final int MSG_AUTH_CANCEL = 3;
    private static final int MSG_AUTH_ERROR = 4;
    private static final int MSG_AUTH_COMPLETE = 5;
    private static final int LOGIN = 7;

    private LoadingDialog loadingDialog;

    @Override
    protected void onResume() {
        super.onResume();
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_register);
        setHasTitle(false);
        ShareSDK.initSDK(this);
        initView();
        initListener();
        new Wechat(this).removeAccount();//清除授权
    }

    private void initView() {
        weixinRegister = (LinearLayout) findViewById(R.id.weixinRegister);
        elseRegister = (TextView) findViewById(R.id.else_register);
        longins = (TextView) findViewById(R.id.longins);
        enter = (TextView) findViewById(R.id.enter);

        if (loadingDialog == null)
            loadingDialog = new LoadingDialog(this);
    }

    private void initListener() {
        weixinRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadingDialog.show();
                weChatLogin();
            }
        });
        elseRegister.setOnClickListener(this);
        longins.setOnClickListener(this);
        enter.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.else_register:
                intent.setClass(this, ElseRegistersActivity.class);
                break;
            case R.id.longins:
                intent.setClass(this, LonginActivity.class);
                break;
            case R.id.enter:
                UserTools.logOut(this);
                intent.setClass(this, MainActivity.class);
                break;
        }
        startActivity(intent);
    }

    //微信登录
    private void weChatLogin() {
        Platform platform = new Wechat(this);
        if (platform.isValid()) {//授权成功后，第三方平台的数据才会在ShareSDK的数据库中
            String userId = platform.getDb().getUserId();
            if (!TextUtils.isEmpty(userId)) {
                String userIcon = platform.getDb().getUserIcon();
                //把微信的图片保存到本地
                new Thread(new MyRunnable(userIcon)).start();
                return;
            }
        }
        platform.setPlatformActionListener(this);//微信登录的回调
        platform.SSOSetting(true);//不使用sso授权
        platform.showUser(null);//请求授权用户的回调
    }

    private String mFileName = "wechat.jpg";
    public final static String wechatImage =
            Environment.getExternalStorageDirectory().getAbsolutePath() + "/wechatImage/";

    class MyRunnable implements Runnable {
        private String filePath;

        public MyRunnable(String filePath) {
            this.filePath = filePath;
        }

        @Override
        public void run() {
            try {
                Bitmap mBitmap = BitmapFactory.decodeStream(getImageStream(filePath));
                saveFile(mBitmap, mFileName);
                UIHandler.sendEmptyMessage(LOGIN, FirstRegisterActivity.this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public InputStream getImageStream(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return conn.getInputStream();
        }
        return null;
    }

    public void saveFile(Bitmap bm, String fileName) throws IOException {
        File dirFile = new File(wechatImage);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(wechatImage + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }

    public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
        if (action == Platform.ACTION_USER_INFOR) {
            UIHandler.sendEmptyMessage(MSG_AUTH_COMPLETE, this);
            login(platform.getName(), platform.getDb().getUserId(), res);
        }
        System.out.println(res);
    }

    public void onError(Platform platform, int action, Throwable t) {
        if (action == Platform.ACTION_USER_INFOR) {
            UIHandler.sendEmptyMessage(MSG_AUTH_ERROR, this);
        }
        t.printStackTrace();
    }

    public void onCancel(Platform platform, int action) {
        if (action == Platform.ACTION_USER_INFOR) {
            UIHandler.sendEmptyMessage(MSG_AUTH_CANCEL, this);
        }
    }

    private void login(String plat, String userId, HashMap<String, Object> userInfo) {
        Message msg = new Message();
        msg.what = MSG_LOGIN;
        msg.obj = plat;
        UIHandler.sendMessage(msg, this);
    }

    public boolean handleMessage(Message msg) {
        loadingDialog.dismiss();
        switch (msg.what) {
            case MSG_LOGIN:
                weChatLogin();
                break;
            case MSG_AUTH_CANCEL:
                Toast.makeText(this, "授权操作已取消", Toast.LENGTH_SHORT).show();
                break;
            case MSG_AUTH_ERROR:
                Toast.makeText(this, "授权操作遇到错误", Toast.LENGTH_SHORT).show();
                break;
            case MSG_AUTH_COMPLETE:
                Toast.makeText(this, "授权成功，正在跳转登录操作…", Toast.LENGTH_SHORT).show();
                break;
            case LOGIN:
                login();
                break;
        }
        return false;
    }


    private void login() {
        Platform platform = new Wechat(this);
        HashMap<String, String> params = new HashMap<>();
        params.put("usid", platform.getDb().getUserId());
        params.put("name", platform.getDb().getUserName());
        params.put("deviceToken", UmengUtils.getToken(this));
        HashMap<String, File> files = new HashMap<>();
        String userIcon = wechatImage + mFileName;
        if (userIcon != null) {
            files.put("files", new File(userIcon));
        }
        loadingDialog.show();
        new ImageUploadAsyncTask(params, files, "file", Constants.LOGIN_WECHAT, new HttpRequest.HttpRequestListener() {
            @Override
            public void httpError() {
                loadingDialog.dismiss();
            }

            @Override
            public void httpSuccess(String msg) {
                loadingDialog.dismiss();
                System.out.println(msg);
                Gson gson = new Gson();
                UserBean entity = gson.fromJson(msg, UserBean.class);
                if (entity.getCode() == 0) {
                    System.out.println("<--------wecaht-------->" + entity.getData().getAcc_token());
                    UserTools.saveUser(FirstRegisterActivity.this, entity.getData());
// 加个登陆试试
                    final UserBean.User user = UserTools.getUser(FirstRegisterActivity.this);
                    EMChatManager.getInstance().login(user.getId() + "", user.getPassword(), new EMCallBack() {
                        @Override
                        public void onSuccess() {
                            //  Toast.makeText(TaPageActivity.this, "chenggong" + MD5.getMD5(MD5.getMD5(user.getPassword())), Toast.LENGTH_SHORT).show();
                            // 登陆成功，保存用户名密码
                            MagicBorrowApplication.getInstance().setUserName(user.getId() + "");
                            MagicBorrowApplication.getInstance().setPassword(user.getPassword());

                            // 更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                            boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick(
                                    user.getNickname());
                            Log.e("环信登录成功", "sssss  " + user.getId() + "  ");
                        }

                        @Override
                        public void onError(int i, String s) {
                            Log.e("环信登录失败", s);
                        }

                        @Override
                        public void onProgress(int i, String s) {

                        }
                    });


                    Toast.makeText(FirstRegisterActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    Intent intent;
                    if (TextUtils.isEmpty(UserTools.getUser(FirstRegisterActivity.this).getMobile())) {
                        intent = new Intent(FirstRegisterActivity.this, WeChatPhoneActivity.class);
                        startActivity(intent);

                    } else {
                        intent = new Intent(FirstRegisterActivity.this, MainActivity.class);
                        startActivity(intent);
                    }
                    finish();
                } else {
                    Toast.makeText(FirstRegisterActivity.this, entity.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        }).execute();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ShareSDK.stopSDK();
    }
}
